//
//  UserAccountViewModel.swift
//  Sinaweibo
//
//  Created by 谌桃 on 15/11/29.
//  Copyright © 2015年 ryan.chen. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class UserAccountViewModel: NSObject {
    
    // MARK:用户逻辑处理
    
    //定义账户属性
    var account: UserAccount?
    
    //重写构造方法
    override init() {
        super.init()
        
        //进行赋值
        account = UserAccount.loadAccount()
    }
    
    //判断是否登录
    var userLogin:Bool{
    
        //token不为空 false true
        return account?.access_token != nil
    }
    
    //token可能为空, 可能不为空
    var token:String?{
    
        return account?.access_token
    }
    
    //用户的头像url
    var userHeadURL:NSURL? {
    
        let url = NSURL(string: account?.avatar_large ?? "")
        
        return url
    }
    
    
    //用户名的计算性属性
    
    var userName: String? {
        return account?.name
    }
    
    
    // MARK:用户网络数据请求与处理
    
    //请求用户Token
    func loadAccessToken(code: String,finished:(error:NSError?)->()){
        
        //获取授权API接口
        let urlString = "oauth2/access_token"
        
        //请求的字段参数 , 字段必须与服务器给定的一样, 否则就无法与服务器正常交互
        let paramters = ["client_id":client_id, "redirect_uri":redirect_uri, "code":code ,"client_secret":secret, "grant_type":"authorization_code"]
        
        NetWorkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: paramters) { (result, error) -> () in
            
            if error != nil {
                
                finished(error: error)
            
                return
            }
            
            //走到这一步, 就一定有结果
            //字典转模型
            let userAccount = UserAccount(dict: result!)
            
            self.loadAccountInfo(userAccount, finished:finished)
        }
    }
    
    //加载用户信息
    private func loadAccountInfo(userAccount: UserAccount, finished:(error:NSError?)->()){
        
        //用户API接口 url
        let urlString = "2/users/show.json"
        
        
        guard let token = userAccount.access_token , uid = userAccount.uid else{
            
            SVProgressHUD.showErrorWithStatus(errorTip)
            
            return
        }
        
        let parameters = ["access_token":token, "uid":uid]
        
       NetWorkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
        
        if error != nil {
        
            finished(error: error)
            
            return
        }
        
        //获取用户头像
        userAccount.avatar_large = result!["avatar_large"] as? String
        
        //获取用户名
        userAccount.name = result!["name"] as? String
        
        //将用户信息保存起来, 用到模型对象进行保存
        userAccount.saveAccount()
        
        finished(error: nil)
        
        }
    }
}
